package com.jqkb.pages;

import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.jqkb.R;
import com.jqkb.service.ActionService;
import com.jqkb.service.util.CallBack;
import com.jqkb.service.util.Converter;
import com.jqkb.service.util.SimpleApi;
import com.jqkb.utils.Constant;
import okhttp3.*;
import retrofit2.Call;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


public class ActionActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {


    Spinner spinner;

    private LinkedList<SelectedFile> selectedFiles = new LinkedList<>();
    private EditText titleEdt;
    private EditText contentEdt;
    private EditText placeEdt;
    private TextView current_tv;
    private Button commitButton;
    private List<String> dataList;
    private String grade;
    private String title;
    private String content;
    private String place;
    private AlertDialog alertDialog;
    private LinearLayout fileContainer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action);

        current_tv = (TextView) findViewById(R.id.current_tv);
        titleEdt = (EditText) findViewById(R.id.titleEdt);
        contentEdt = (EditText) findViewById(R.id.contentEdt);
        placeEdt = (EditText) findViewById(R.id.placeEdt);
        commitButton = (Button) findViewById(R.id.commitBtn);
        spinner = (Spinner) findViewById(R.id.numberSpinner);
        fileContainer = (LinearLayout) findViewById(R.id.filesContainer);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ActionActivity.this, android.R.layout.simple_spinner_item, getData());
        spinner.setAdapter(adapter);

        commitButton.setOnClickListener(this);
        spinner.setOnItemSelectedListener(this);
        updateCurrentTime();
    }

    private void updateCurrentTime() {
        current_tv.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) return;
                current_tv.setText(String.format("%tF %1$tT", new Date()));
                updateCurrentTime();
            }
        }, 1000);

    }

    private List<String> getData() {
        this.dataList = new ArrayList<>();
        this.dataList.add("一般");
        this.dataList.add("紧急");
        this.dataList.add("危急");
        return this.dataList;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.commitBtn:
                this.title = titleEdt.getText().toString().trim();
                this.content = contentEdt.getText().toString().trim();
                this.place = placeEdt.getText().toString().trim();
                if (title.trim().isEmpty()) {
                    Toast.makeText(ActionActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (content.trim().isEmpty()) {
                    Toast.makeText(ActionActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(this, SelectTargetActivity.class);
                    startActivityForResult(intent, Constant.OPEN_SELECT_TARGET);
                }
                break;
            case R.id.openCameraTv:
                alertDialog.dismiss();
                if (selectedFiles.size() > 5) {
                    Toast.makeText(this, "最多可选5个文件, 长按可以移除", Toast.LENGTH_SHORT).show();
                } else {
                    openCamera();
                }
                break;
            case R.id.openPhotoTv:
                alertDialog.dismiss();
                chooseFile(Constant.OPEN_PHOTO, "image/*");
                break;
            case R.id.cancelTv:
                alertDialog.dismiss();
                break;
            case R.id.openMp3Tv:
                alertDialog.dismiss();
                chooseFile(Constant.OPEN_AUDIO, "audio/*");
                break;
            case R.id.openMoviesTv:
                alertDialog.dismiss();
                chooseFile(Constant.OPEN_MOVIE, "video/*");
                break;

            case R.id.openFile:
                alertDialog.dismiss();
                chooseFile(Constant.OPEN_FILE, "*/*");
                break;
        }

    }

    private void chooseFile(int requestCode, String contentType) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(contentType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, requestCode);
    }


    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DCIM);
        file = new File(file, "JQKB-" + System.nanoTime() + ".jpg");
        file.getParentFile().mkdirs();

        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.jqkb.FileProvider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        //预先保存到集合之中
        SelectedFile selectedPictureFile = new SelectedFile(file, Constant.OPEN_CAMERA);
        selectedPictureFile.uri = uri;
        selectedFiles.add(selectedPictureFile);
        startActivityForResult(intent, Constant.OPEN_CAMERA);
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        this.grade = dataList.get(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public static class SelectedFile {
        public File file;
        public Uri uri;
        public String name;
        public long length;
        public int type;

        public SelectedFile(File file, int type) {
            this.file = file;
            this.name = file.getName();
            this.length = file.length();
            this.type = type;
        }

        public SelectedFile(Uri uri, String name, Long length, int type) {
            this.uri = uri;
            this.name = name;
            this.length = length;
            this.type = type;
        }

        public boolean isFile() {
            return file != null;
        }
    }

    /**
     * 处理窗口返回值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && resultCode == Constant.OPEN_SELECT_TARGET) {
            ArrayList<String> ids = data.getStringArrayListExtra("users");
            Long[] targetIds = new Long[ids.size()];
            for (int i = 0; i < ids.size(); i++) {
                String id = ids.get(i);
                targetIds[i] = new Long(id);
            }

            ActionService service = SimpleApi.create(ActionService.class);
            MultipartBody.Part[] parts = null;
            long totalLength = 0;
            if (!selectedFiles.isEmpty()) {
                parts = new MultipartBody.Part[selectedFiles.size()];
                for (int i = 0; i < selectedFiles.size(); i++) {
                    SelectedFile selectedFile = selectedFiles.get(i);
                    totalLength += selectedFile.length;
                    MediaType contentType = MediaType.parse(("multipart/form-data"));
                    if (selectedFile.type == Constant.OPEN_CAMERA) {
                        try {
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedFile.uri));
                            Matrix matrix = new Matrix();
                            int height = bitmap.getHeight();
                            if (height > 1920) {
                                //缩小
                                float scalePresent = (1920f / height);
                                matrix.postScale(scalePresent, scalePresent);
                                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                            }

                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                            RequestBody multipartBody = MultipartBody.create(contentType, byteArrayOutputStream.toByteArray());
                            MultipartBody.Part part = MultipartBody.Part.createFormData("file", selectedFile.name, multipartBody);
                            parts[i] = part;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (selectedFile.uri != null) {
                        try {
                            Uri uri = selectedFile.uri;
                            InputStream inputStream = getContentResolver().openInputStream(uri);
                            byte[] bytes = new byte[inputStream.available()];
                            inputStream.read(bytes);
                            inputStream.close();
                            RequestBody multipartBody = MultipartBody.create(contentType, bytes);
                            MultipartBody.Part part = MultipartBody.Part.createFormData("file", selectedFile.name, multipartBody);
                            parts[i] = part;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (selectedFile.file != null) {
                        try {

                            InputStream inputStream = openFileInput(selectedFile.file.toString());
                            byte[] bytes = new byte[(int) selectedFile.length];
                            inputStream.read(bytes);
                            inputStream.close();
                            RequestBody multipartBody = MultipartBody.create(contentType, bytes);
                            MultipartBody.Part part = MultipartBody.Part.createFormData("file", selectedFile.name, multipartBody);
                            parts[i] = part;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

            AlertDialog.Builder builder = new AlertDialog.Builder(ActionActivity.this);
            View inflateView = LayoutInflater.from(ActionActivity.this).inflate(R.layout.upload_layout, null);
            builder.setView(inflateView);
            builder.setTitle(MessageFormat.format("总文件大小：{0,number,0.00}MB", totalLength / 1024 / 1024d));
            builder.setCancelable(false);

            final AlertDialog alertDialog = builder.create();
            alertDialog.show();

            RequestBody contentBody =
                    RequestBody.create(
                            MediaType.parse("multipart/form-data"), content);
            final Call<ResponseBody> call = service.actionAdd(title, contentBody, place, grade, parts, targetIds);


            Converter.convert(Object.class, call, new CallBack<Object>() {
                @Override
                public void onSuccess(Object object, JsonNode data) {
                    if (data.path("code").asInt() == 2000) {
                        titleEdt.setText("");
                        contentEdt.setText("");
                        placeEdt.setText("");
                        selectedFiles.clear();
                        fileContainer.removeAllViews();
                    }
                    Toast.makeText(ActionActivity.this, data.path("message").asText(), Toast.LENGTH_SHORT).show();
                    alertDialog.dismiss();
                }

                @Override
                public void onFail(boolean success, int code, String message, JsonNode data) {
                    Toast.makeText(ActionActivity.this, message, Toast.LENGTH_SHORT).show();
                    alertDialog.dismiss();
                }

                @Override
                public void onNetworkFail(Call<ResponseBody> jsonNode) {
                    alertDialog.dismiss();
                }

                @Override
                public void onError(Call<ResponseBody> response) {
                    alertDialog.dismiss();
                }
            });


        } else if (requestCode == Constant.OPEN_CAMERA) {
            if (resultCode == 0) {
                selectedFiles.removeLast();
                Toast.makeText(this, "拍照取消", Toast.LENGTH_SHORT).show();
            } else {
//                Toast.makeText(this, "拍照成功:" + data, Toast.LENGTH_SHORT).show();
                showFilesIcon();
            }

        } else if (requestCode == Constant.OPEN_PHOTO || requestCode == Constant.OPEN_FILE || requestCode == Constant.OPEN_AUDIO
                || requestCode == Constant.OPEN_MOVIE) {
            if (resultCode == 0) {
                Toast.makeText(this, "取消选择", Toast.LENGTH_SHORT).show();
            } else if (resultCode == -1) {
                try {
                    Uri uri = data.getData();
                    SelectedFile selectedFile = null;

                    if (uri.toString().startsWith("file:///")) {
                        selectedFile = new SelectedFile(new File(uri.toString()), requestCode);
                    } else {
                        String[] proj = {
                                MediaStore.Files.FileColumns.SIZE,
                                MediaStore.Files.FileColumns.DISPLAY_NAME,
                        };
                        Cursor actualimagecursor = this.getContentResolver().query(uri, proj, null, null, null);
                        actualimagecursor.moveToFirst();
                        long fileLength = actualimagecursor.getLong(actualimagecursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE));
                        String displayName = actualimagecursor.getString(actualimagecursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME));

                        selectedFile = new SelectedFile(uri, displayName, fileLength, requestCode);
                    }

                    int MB100 = 1024 * 1024 * 100;
                    if (selectedFile.length < MB100) {
                        selectedFiles.add(selectedFile);
                        showFilesIcon();
                        Toast.makeText(this, "已选择", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "选择的文件大小不能大于100M", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

    }

    private void showFilesIcon() {
        fileContainer.removeAllViews();//清空以前的数据
        for (int i = 0; i < selectedFiles.size(); i++) {
            final SelectedFile item = selectedFiles.get(i);
            String fileName = item.name;

            final ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
            params.gravity = Gravity.CENTER;
            params.setMargins(5, 5, 5, 5);
            imageView.setLayoutParams(params);

            if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")) {
                imageView.setImageResource(R.mipmap.jpg);
            } else if (fileName.endsWith(".mp3") || fileName.endsWith(".arm") || fileName.endsWith(".acc") || fileName.endsWith(".ogg")) {
                imageView.setImageResource(R.mipmap.audio);
            } else if (fileName.endsWith(".mp4")) {
                imageView.setImageResource(R.mipmap.mpg);
            } else if (fileName.endsWith(".pdf")) {
                imageView.setImageResource(R.mipmap.pdf);
            } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".ppt") || fileName.endsWith(".pptx") || fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                imageView.setImageResource(R.mipmap.office);
            } else {
                imageView.setImageResource(R.mipmap.other);
            }

            imageView.setLongClickable(true);
            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    selectedFiles.remove(item);
                    fileContainer.removeView(imageView);
                    return true;
                }
            });

            fileContainer.addView(imageView);
        }

    }

    public void openFile(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View alertView = LayoutInflater.from(this).inflate(R.layout.file_select_alert_item, null);
        alertView.findViewById(R.id.openCameraTv).setOnClickListener(this);
        alertView.findViewById(R.id.openPhotoTv).setOnClickListener(this);
        alertView.findViewById(R.id.openMp3Tv).setOnClickListener(this);
        alertView.findViewById(R.id.openMoviesTv).setOnClickListener(this);
        alertView.findViewById(R.id.cancelTv).setOnClickListener(this);
        alertView.findViewById(R.id.openFile).setOnClickListener(this);
        builder.setView(alertView);
        alertDialog = builder.create();
        alertDialog.show();

    }
}
